
<!DOCTYPE HTML>

<html>

<head>
	<meta charset="utf-8">
	<title>使用PHP和AJAX制作日历 - 前端艺术</title>
	<meta name="author" content="Nicholas">

	
	<meta name="description" content="使用PHP和AJAX制作日历 在很多网站，日历是一个必要的组成部分。通常这些日历是jquery的一个插件，但是也可以用php来实现。今天我将使用ajax技术展示一个月份的日历，可以通过左右箭头切换月份。由于是ajax,这个日历还有其他的优点，它是一个响应式的移动日历。在开始编写代码之前， &hellip;">
	

  <!-- http://t.co/dKP3o1e -->
  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="viewport" content="width=device-width, initial-scale=1">

	<link href="/atom.xml" rel="alternate" title="前端艺术" type="application/atom+xml">
	
	<link rel="canonical" href="http://xiebaochun.github.io/blog/2013/09/27/php-ajax-calender/">
	<link href="/favicon.png" rel="shortcut icon">
	<link href="/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">
	<link href="/stylesheets/font-awesome.min.css" media="screen, projection" rel="stylesheet" type="text/css">
	<!--[if lt IE 9]><script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
	<link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,400,700' rel='stylesheet' type='text/css'>
	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
	<!--Fonts from Google"s Web font directory at http://google.com/webfonts -->
<link href="http://fonts.googleapis.com/css?family=PT+Serif:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=PT+Sans:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">

</head>


<body>
	<div class="container">
		<div class="left-col">
			<div class="intrude-less">
			<header id="header" class="inner"><div class="profilepic">
<!--the weather pugin-->
    <script defer src="http://julying.com/lab/weather/v3/jquery.weather.build.min.js?parentbox=body&moveArea=all&zIndex=1&move=1&drag=1&autoDrop=1&styleSize=big&style=_random&area=client&city=%E5%8C%97%E4%BA%AC"></script>
	<script src="/javascripts/md5.js"></script>
	<script type="text/javascript">
		$(function(){
			$('.profilepic').append("<img src='https://si0.twimg.com/profile_images/378800000316979686/061b0d73fe1b9cc3a643a68bcb077161.jpeg' alt='Profile Picture' style='width: 160px;' />");
		});
	</script>
</div>
<hgroup>
  <h1><a href="/">前端艺术</a></h1>
  
    <h2>one blog for games.</h2>
  
</hgroup>

<nav id="main-nav"><ul class="main-navigation">
  <li><a href="/">Home</a></li>
  <li><a href="/blog/archives">Archives</a></li>
  <li><a href="http://www.juerry.com/index.html">my lab</a></li>
</ul>


<section class="aboutme">
  <p>
    专注于移动开发
  </p>
</section>
</nav>
<nav id="sub-nav">
	<div class="social">
		
		
		
		<a class="twitter" href="http://twitter.com/xiebaochun" title="Twitter">Twitter</a>
		
		
		<a class="github" href="https://github.com/xiebaochun" title="GitHub">GitHub</a>
		
		
		
		
		
		
		
		
		<a class="rss" href="/atom.xml" title="RSS">RSS</a>
		
	</div>
</nav>
<section>
  <h1>Categories</h1>
    <ul id="category-list"><li><a href='/blog/categories/ios/'>ios (2)</a></li><li><a href='/blog/categories/other/'>other (14)</a></li><li><a href='/blog/categories/web/'>web (23)</a></li></ul>
</section>

</header>				
			</div>
		</div>	
		<div class="mid-col">
			
				
			
			<div class="mid-col-container">
				<div id="content" class="inner"><article class="post" itemscope itemtype="http://schema.org/BlogPosting">
	<h1 class="title" itemprop="name">使用PHP和AJAX制作日历</h1>
	<div class="entry-content" itemprop="articleBody"><p>在很多网站，日历是一个必要的组成部分。通常这些日历是jquery的一个插件，但是也可以用php来实现。今天我将使用ajax技术展示一个月份的日历，可以通过左右箭头切换月份。由于是ajax,这个日历还有其他的优点，它是一个响应式的移动日历。在开始编写代码之前，我建议你先看看我们的demo.</p>

<p><img src="http://www.script-tutorials.com/demos/361/php_ajax_calendar.png" alt="" /></p>

<p><a href="http://www.script-tutorials.com/demos/361/">在线演示</a>
<a href="http://www.script-tutorials.com/demos/361/source.zip">下载源文件</a></p>

<hr />
<p>文件结构：</p>

<p>在开始之前，让我们先为我们的文件定义一个清晰的文件夹结构：</p>

<ul>
  <li>css-存放所有的css文件</li>
  <li>images-存放所有可能用到的图片</li>
  <li>templates-存放所有的模板文件
<!--more-->
### 第一步 编写HTML文件 ###</li>
</ul>

<p>我们不使用任何特定的系统模板（如Smarty），我们将只使用我们自己写的一个简单的html模板。</p>

<p>templates/index.html</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="utf-8" /&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /&gt;
&lt;title&gt;PHP AJAX Calendar&lt;/title&gt;

&lt;!-- add styles and scripts --&gt;
&lt;link href="css/styles.css" rel="stylesheet" type="text/css" /&gt;
&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id="calendar"&gt;
__calendar__
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>这个一个非常简单的index页面模板，我们在这定义了一个日历的父容器。另一个模板将会被用作日历的内部容器。</p>

<p>templates/celendar.html</p>

<pre><code>&lt;div class="navigation"&gt;
&lt;a class="prev" href="index.php?month=__prev_month__" onclick="$('#calendar').load('index.php?month=__prev_month__&amp;_r=' + Math.random()); return false;"&gt;&lt;/a&gt;
&lt;div class="title" &gt;__cal_caption__&lt;/div&gt;
&lt;a class="next" href="index.php?month=__next_month__" onclick="$('#calendar').load('index.php?month=__next_month__&amp;_r=' + Math.random()); return false;"&gt;&lt;/a&gt;
&lt;/div&gt;

&lt;table&gt;
&lt;tr&gt;
&lt;th class="weekday"&gt;sun&lt;/th&gt;
&lt;th class="weekday"&gt;mon&lt;/th&gt;
&lt;th class="weekday"&gt;tue&lt;/th&gt;
&lt;th class="weekday"&gt;wed&lt;/th&gt;
&lt;th class="weekday"&gt;thu&lt;/th&gt;
&lt;th class="weekday"&gt;fri&lt;/th&gt;
&lt;th class="weekday"&gt;sat&lt;/th&gt;
&lt;/tr&gt;
__cal_rows__
&lt;/table&gt;
</code></pre>

<p>这是因为对于ajax的请求，我们不需要返回任何东西，除了内部的日历内容。</p>

<h3 id="php">第二步 PHP</h3>

<p>给日历添加行为</p>

<p>index.php</p>

<pre><code>// Get current year, month and day
list($iNowYear, $iNowMonth, $iNowDay) = explode('-', date('Y-m-d'));

// Get current year and month depending on possible GET parameters
if (isset($_GET['month'])) {
list($iMonth, $iYear) = explode('-', $_GET['month']);
$iMonth = (int)$iMonth;
$iYear = (int)$iYear;
} else {
list($iMonth, $iYear) = explode('-', date('n-Y'));
}

// Get name and number of days of specified month
$iTimestamp = mktime(0, 0, 0, $iMonth, $iNowDay, $iYear);
list($sMonthName, $iDaysInMonth) = explode('-', date('F-t', $iTimestamp));

// Get previous year and month
$iPrevYear = $iYear;
$iPrevMonth = $iMonth - 1;
if ($iPrevMonth &lt;= 0) {
$iPrevYear--;
$iPrevMonth = 12; // set to December
}

// Get next year and month
$iNextYear = $iYear;
$iNextMonth = $iMonth + 1;
if ($iNextMonth &gt; 12) {
$iNextYear++;
$iNextMonth = 1;
}

// Get number of days of previous month
$iPrevDaysInMonth = (int)date('t', mktime(0, 0, 0, $iPrevMonth, $iNowDay, $iPrevYear));

// Get numeric representation of the day of the week of the first day of specified (current) month
$iFirstDayDow = (int)date('w', mktime(0, 0, 0, $iMonth, 1, $iYear));

// On what day the previous month begins
$iPrevShowFrom = $iPrevDaysInMonth - $iFirstDayDow + 1;

// If previous month
$bPreviousMonth = ($iFirstDayDow &gt; 0);

// Initial day
$iCurrentDay = ($bPreviousMonth) ? $iPrevShowFrom : 1;

$bNextMonth = false;
$sCalTblRows = '';

// Generate rows for the calendar
for ($i = 0; $i &lt; 6; $i++) { // 6-weeks range
$sCalTblRows .= '&lt;tr&gt;';
for ($j = 0; $j &lt; 7; $j++) { // 7 days a week

$sClass = '';
if ($iNowYear == $iYear &amp;&amp; $iNowMonth == $iMonth &amp;&amp; $iNowDay == $iCurrentDay &amp;&amp; !$bPreviousMonth &amp;&amp; !$bNextMonth) {
$sClass = 'today';
} elseif (!$bPreviousMonth &amp;&amp; !$bNextMonth) {
$sClass = 'current';
}
$sCalTblRows .= '&lt;td class="'.$sClass.'"&gt;&lt;a href="javascript: void(0)"&gt;'.$iCurrentDay.'&lt;/a&gt;&lt;/td&gt;';

// Next day
$iCurrentDay++;
if ($bPreviousMonth &amp;&amp; $iCurrentDay &gt; $iPrevDaysInMonth) {
$bPreviousMonth = false;
$iCurrentDay = 1;
}
if (!$bPreviousMonth &amp;&amp; !$bNextMonth &amp;&amp; $iCurrentDay &gt; $iDaysInMonth) {
$bNextMonth = true;
$iCurrentDay = 1;
}
}
$sCalTblRows .= '&lt;/tr&gt;';
}

// Prepare replacement keys and generate the calendar
$aKeys = array(
'__prev_month__' =&gt; "{$iPrevMonth}-{$iPrevYear}",
'__next_month__' =&gt; "{$iNextMonth}-{$iNextYear}",
'__cal_caption__' =&gt; $sMonthName . ', ' . $iYear,
'__cal_rows__' =&gt; $sCalTblRows,
);
$sCalendarItself = strtr(file_get_contents('templates/calendar.html'), $aKeys);

// AJAX requests - return the calendar
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' &amp;&amp; isset($_GET['month'])) {
header('Content-Type: text/html; charset=utf-8');
echo $sCalendarItself;
exit;
}

$aVariables = array(
'__calendar__' =&gt; $sCalendarItself,
);
echo strtr(file_get_contents('templates/index.html'), $aVariables);
</code></pre>

<p>我尽量为每行代码都加上了注释，目的是为了让你更加容易理解整个处理过程。开始我们创建了日历相关的当前日期很请求日期。然后我们生成日历表格，最后我们将模板的关键字替换掉。在Ajax请求时，我们只翻译日历内部的内容($sCalendarItself)，否则我们将显示整个页面。</p>

<h3 id="css">第三步 CSS</h3>

<p>现在，我们的日历看起来不那么美观，因为只有html代码。让我们装饰一下我们的日历吧！</p>

<p>css/style.css</p>

<pre><code>/* calendar styles */
#calendar {
-moz-user-select: none;
border: 1px solid #EEEEEE;
border-radius: 6px 6px 6px 6px;
color: #333333;
font-family: Arial,sans-serif;
font-size: 1.1em;
margin: 10px auto;
padding: 0.4em;
width: 90%;
}
#calendar .navigation {
background-color: #CC0000;
border: 1px solid #E3A1A1;
border-radius: 6px 6px 6px 6px;
color: #FFFFFF;
font-weight: bold;
padding: 1px;
position: relative;
}
#calendar .navigation .title {
background: none repeat scroll 0 0 transparent;
border-color: rgba(0, 0, 0, 0);
color: inherit;
line-height: 1.8em;
margin: 0 2.3em;
text-align: center;
}
#calendar .navigation .prev, #calendar .navigation .next {
background-image: url(../images/nav.png);
height: 24px;
opacity: 0.9;
position: absolute;
top: 4px;
width: 24px;
}
#calendar .navigation .prev {
background-position: 0 0;
left: 4px;
}
#calendar .navigation .next {
background-position: -24px 0;
right: 4px;
}
#calendar .navigation .prev:hover, #calendar .navigation .next:hover {
opacity: 1;
}
#calendar table {
border-collapse: collapse;
font-size: 0.9em;
table-layout: fixed;
width: 100%;
}
#calendar table th {
border: 0 none;
font-weight: bold;
padding: 0.7em 0.3em;
text-align: center;
}
#calendar table td {
border: 0 none;
padding: 1px;
}
#calendar table td a {
background-color: #EEEEEE;
border: 1px solid #D8DCDF;
color: #004276;
display: block;
font-weight: normal;
opacity: 0.7;
padding: 0.2em;
text-align: right;
text-decoration: none;
}
#calendar table td a:hover {
background-color: #F6F6F6;
border: 1px solid #CDD5DA;
color: #111111;
}
#calendar table td.current a {
font-weight: bold;
opacity: 1;
}
#calendar table td.today a {
background-color: #FBF8EE;
border: 1px solid #FCD3A1;
color: #444444;
font-weight: bold;
opacity: 1;
}
</code></pre>

<h3 id="section">第四步 图片</h3>

<p>这里只要使用一个很小的导航图片就行了</p>

<p><img src="http://www.script-tutorials.com/demos/361/images/nav.png" alt="" /></p>

<h3 id="section-1">总结</h3>

<p>这就是今天的所有内容，我们只是准备了响应式风格的日历。感谢你耐心看完本文，如果你喜欢的话，请使用下面的社交工具将它分享给你的朋友吧！</p>

<p>原文地址：<a href="http://www.script-tutorials.com/php-ajax-calendar/">http://www.script-tutorials.com/php-ajax-calendar/</a></p>
</div>

</article>

	<div class="share">
	<div class="addthis_toolbox addthis_default_style ">
	
	
	<a class="addthis_button_tweet"></a>
	
	
	
	<!-- JiaThis Button BEGIN -->
<div class="jiathis_style_32x32">
	<a class="jiathis_button_qzone"></a>
	<a class="jiathis_button_tsina"></a>
	<a class="jiathis_button_tqq"></a>
	<a class="jiathis_button_weixin"></a>
	<a class="jiathis_button_renren"></a>
	<a href="http://www.jiathis.com/share?uid=1838235" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
	<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
var jiathis_config = {data_track_clickback:'true'};
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=1371541356556113" charset="utf-8"></script>
<!-- JiaThis Button END -->
<!-- UY BEGIN -->
<div id="uyan_frame"></div>
<script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=1838235"></script>
<!-- UY END -->
	
	<a class="addthis_counter addthis_pill_style"></a>
	</div>
  <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid="></script>
</div>


</div>
			</div>
			<footer id="footer" class="inner"><p>
  Copyright &copy; 2014 - Nicholas -
  <span class="credit">Powered by <a href="http://octopress.org">Octopress</a></span>
</p>

Design credit: <a href="http://shashankmehta.in/archive/2012/greyshade.html">Shashank Mehta</a></footer>
			







  <script type="text/javascript">
    (function(){
      var twitterWidgets = document.createElement('script');
      twitterWidgets.type = 'text/javascript';
      twitterWidgets.async = true;
      twitterWidgets.src = '//platform.twitter.com/widgets.js';
      document.getElementsByTagName('head')[0].appendChild(twitterWidgets);
    })();
  </script>





		</div>
	</div>
</body>
</html>
